#include"ChatController.h"
#include"../event/SignalManager.h"
#include"../MessageIDConst.h"
#include"../Common.h"
#include"../ServerMaster.h"
#include"../UserBaseController.h"
#include"../GameServer.h"

ChatController::ChatController(Object* master)
{
	m_master = master;
	SignalManager::getInstance()->add(ID_C2S_Chat, handler(this, SEL_EVENTFUNC(ChatController::C2S_Chat)));
}

ChatController::~ChatController()
{
}

void ChatController::C2S_Chat(Json::Value& message)
{
	auto sock = message[RECV_SOCK].asInt64();
	auto userId = message["receiveId"].asInt();
	auto content = message["content"].asString();
	auto master = dynamic_cast<ServerMaster*>(m_master);
	auto userBase = master->getModule<UserBaseController>();
	const Player* player = userBase->getPlayer(userId);
	auto senderId = userBase->geUserIdBySock(sock);
	const Player* sender = userBase->getPlayer(senderId);
	Json::Value smessage;
	smessage[MESSAGE_ID] = ID_S2C_Chat;
	smessage["senderId"] = senderId;
	smessage["receiveId"] = userId;
	smessage["content"] = content;
	if (player != nullptr)
	{
		smessage["name"] = player->name;
	}
	else
	{
		smessage["name"] = "";
	}
	master->getGameServer()->Send(sock, smessage);
	if (player != nullptr)
	{
		smessage["name"] = sender->name;
		master->getGameServer()->Send(player->sock, smessage);
	}
}
